import axios from 'axios'
axios.defaults.timeout = 10000;
import {getToken,getClientId} from '@/libs/util'
import config from '@/config'
const host = process.env.NODE_ENV === 'development' ? config.host.dev : config.host.pro
import vue from "@/main";

let count = 0
import NProgress from 'nprogress'


class HttpRequest {
  constructor (baseUrl = baseURL) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig () {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Authorization' : 'Bearer ' + getToken(),
        'ClientId': getClientId()
      }
    }
    return config
  }
  destroy (url) {
    delete this.queue[url]
    if(Object.keys(this.queue).length == 0) {
      NProgress.done()
    }
  }
  interceptors (instance, url, errMsg) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      const { data } = res
      if(data.code == 403) {
        window.location.reload()
        return
      }
      if(data.code == 401) {
        return
      }
      if(data.code != 200) {
        if(!data.msg) {
          data.msg = '请求发生错误'
        }
        vue.$message.error(data.msg)
      }
      return data
    }, (error) => {
      this.destroy(url)
      let status = error.response.status
      let msg = ''
      switch (status) {
        case 404:
          msg = '404，请检查网络连接'
          break
        case 503:
          msg = '服务间调用失败'
          break
        case 500:
          msg = '服务未捕获的异常'
          break
      }
      if(errMsg) {
        vue.$message.error(errMsg + '失败，原因：' + msg)
      }else {
        vue.$message.error(msg)
      }
      return Promise.reject(error)
    })
  }
  request (options) {
    NProgress.start()
    const instance = axios.create()
    if(options.ignoreBaseUrl){
      options.baseURL = ''
    }
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url, options.errMsg)
    return instance(options)
  }
}
export default HttpRequest
